package com.siashan.unipay4j.wx.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.siashan.unipay4j.core.IPayConfig;
import com.siashan.unipay4j.core.Result;
import com.siashan.unipay4j.core.TradeStateEnum;
import com.siashan.unipay4j.core.UnipayConst;
import com.siashan.unipay4j.core.pay.IQuery;
import com.siashan.unipay4j.core.pay.PayQueryModel;
import com.siashan.unipay4j.core.pay.PayResponse;
import com.siashan.unipay4j.core.util.EnumUtil;
import com.siashan.unipay4j.core.util.MoneyUtil;
import com.siashan.unipay4j.core.util.StrUtil;
import com.siashan.unipay4j.wx.AbstractWxPay;
import com.siashan.unipay4j.wx.WxPayVersionEnum;
import com.siashan.unipay4j.wx.model.QueryOrderResult;
import com.siashan.unipay4j.wx.sdk.WXPayConstants;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import static org.apache.http.HttpStatus.SC_MULTIPLE_CHOICES;
import static org.apache.http.HttpStatus.SC_OK;

/**
 * 支付结果查询
 * 该接口提供所有微信支付订单的查询，商户可以通过该接口主动查询订单状态，完成下一步的业务逻辑。
 * <p>
 * 需要调用查询接口的情况：
 * <p>
 * ◆ 当商户后台、网络、服务器等出现异常，商户系统最终未接收到支付通知；
 * ◆ 调用支付接口后，返回系统错误或未知交易状态情况；
 * ◆ 调用被扫支付API，返回USERPAYING的状态；
 * ◆ 调用关单或撤销接口API之前，需确认支付状态；
 *
 * @author siashan
 * @since v1.0.1
 **/
@Slf4j
public class WxPayQuery extends AbstractWxPay implements IQuery {

    public WxPayQuery() {
        super();
    }

    public WxPayQuery(IPayConfig payConfig) {
        super(payConfig);
    }

    /**
     * 查询支付结果
     *
     * @param model 查询参数
     * @return 支付查询结果
     */
    @Override
    public Result<PayResponse> execQuery(PayQueryModel model) {
        WxPayVersionEnum ver = EnumUtil.getIEnum(WxPayVersionEnum.class, wxPayConfig.getVersion());
        Result result = null;
        switch (ver) {
            case V2:
                result = doQueryV2(model);
                break;
            case V3:
                result = doQueryV3(model);
                break;
            default:
                break;
        }
        return result;
    }


    /**
     * 查询订单V2
     *
     * @param model 查询条件
     * @return 查询结果
     */
    private Result<PayResponse> doQueryV2(PayQueryModel model) {
        log.info("WxQuery::=>订单{} 请求到达", model.getOrderNo());
        try {
            // 查询订单状态
            Map<String, String> map = wrapQueryParam(model);
            Map<String, String> r = initWxPay().orderQuery(map);
            log.info("WxQuery::=>订单{} 返回报文，{}", model.getOrderNo(), r);
            String returnCode = r.get(WXPayConstants.RETURN_CODE);
            if (UnipayConst.SUCCESS.equals(returnCode)) {
                if (WxTradeStateEnum.SUCCESS.getValue().equals(r.get(WXPayConstants.RESULT_CODE))) {
                    return Result.tradeSuccess(wrapperPayResponse(r));
                } else {
                    String errCode = r.get(WXPayConstants.ERR_CODE);
                    String errCodeDes = r.get(WXPayConstants.ERR_CODE_DES);
                    log.info("WxQuery::=>订单{} 查询失败,错误代码{},错误原因{}", model.getOrderNo(), errCode, errCodeDes);
                    return Result.returnFail(errCode, errCodeDes);
                }
            } else {
                String returnMsg = r.get(WXPayConstants.RETURN_MSG);
                log.info("WxQuery::=>订单{} 查询失败,错误代码{},错误原因{}", model.getOrderNo(), returnCode, returnMsg);
                return Result.returnFail(returnCode, returnMsg);
            }

        } catch (Exception e) {
            log.warn("WxQuery=>订单{} 查询时发生异常", model.getOrderNo(), e);
        }
        return Result.exception();
    }


    /**
     * 查询订单V3
     *
     * @param model 查询条件
     * @return 查询结果
     */
    private Result<PayResponse> doQueryV3(PayQueryModel model) {
        log.info("WxQuery::=>订单{} 请求到达", model.getOrderNo());
        // 如果微信支付平台返回的交易号不为空，优先根据微信支付交易号查询，如果为空则根据平台交易号查询
        WechatPayHttpClientBuilder builder = loadBuilder();
        CloseableHttpClient httpClient = builder.build();
        HttpGet httpGet = getHttpGet(model);
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            String body = EntityUtils.toString(response.getEntity());
            log.info("WxQuery::=>订单{} 返回报文，{}", model.getOrderNo(), body);
            if (statusLine.getStatusCode() >= SC_OK && statusLine.getStatusCode() < SC_MULTIPLE_CHOICES) {
                QueryOrderResult queryResult = JSON.parseObject(body, QueryOrderResult.class);
//                if (WxTradeStateEnum.SUCCESS.getValue().equals(queryResult.getTradeState())) {
//                    return Result.tradeSuccess(wrapperPayResponse(queryResult));
//                }
                return Result.returnSuccess(wrapperPayResponse(queryResult));
            } else {
                JSONObject bodyJson = JSON.parseObject(body);
                String errCode = bodyJson.getString(WXPayConstants.CODE);
                String errCodeDes = bodyJson.getString(WXPayConstants.MESSAGE);
                log.info("WxQuery::=>订单{} 查询失败,错误代码{},错误原因{}", model.getOrderNo(), errCode, errCodeDes);
                return Result.returnFail(errCode, errCodeDes);
            }
        } catch (Exception e) {
            log.warn("WxQuery=>订单{} 查询时发生异常", model.getOrderNo(), e);
            return Result.exception();
        }
    }

    private PayResponse wrapperPayResponse(QueryOrderResult result) {
        TradeStateEnum stateEnum = EnumUtil.getIEnum(WxTradeStateEnum.class, result.getTradeState()).getTradeState();
        PayResponse response = new PayResponse();
        response.setTradeState(stateEnum);
        response.setTradeStateDesc(stateEnum.getDesp());
        response.setOutTradeNo(result.getOutTradeNo());
        response.setTradeNo(result.getTransactionId());
        response.setTotalAmount(MoneyUtil.cent2Yuan(result.getAmount().getTotal()));
        response.setBody(result);
        return response;
    }


    private HttpGet getHttpGet(PayQueryModel model) {
        HttpGet httpGet = null;
        if (StrUtil.isNotEmpty(model.getTradeNo())) {
            httpGet = initHttpGet(wrapTransactionIdeUrl(model.getTradeNo()));
        } else {
            httpGet = initHttpGet(wrapOutTradeNoQueryUrl(model.getOutTradeNo()));
        }
        return httpGet;
    }

    private HttpGet initHttpGet(String url) {

        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            uriBuilder.setParameter("mchid", wxPayConfig.getMchId());
            HttpGet httpGet = new HttpGet(uriBuilder.build());


            httpGet.addHeader("Accept", "application/json");
            httpGet.addHeader("Content-type", "application/json; charset=utf-8");
            return httpGet;
        } catch (URISyntaxException e) {
            log.warn("构建支付查询请求Url异常", e);
            throw new RuntimeException();
        }
    }


    private String wrapOutTradeNoQueryUrl(String outTradeNo) {
        return WXPayConstants.V3_PAY_URL_QUERY_BY_OUTTRADE_NO.replace("{out_trade_no}", outTradeNo.trim());
    }

    private String wrapTransactionIdeUrl(String transactionId) {
        return WXPayConstants.V3_PAY_URL_QUERY_BY_TRANSACTION_ID.replace("{transaction_id}", transactionId.trim());
    }


    /**
     * 封装订单查询参数
     *
     * @param model 查询请求参数
     * @return 封装后的参数
     */
    private Map<String, String> wrapQueryParam(PayQueryModel model) {
        Map<String, String> map = new HashMap<>();
        if (StrUtil.isNotEmpty(model.getTradeNo())) {
            map.put("transaction_id", model.getTradeNo());
        }
        if (StrUtil.isNotEmpty(model.getOutTradeNo())) {
            map.put("out_trade_no", model.getOutTradeNo());
        }
        return map;
    }

}
